package com.java.traiing.car;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CarDaoImpl implements CarDao {

	public List<Car> getallCar() {

		Connection connection = null;
		Statement statement = null;
		ResultSet resultset = null;
		
		try{
			
		
		connection = getConnection();
		statement=connection.createStatement();
		resultset=statement.executeQuery("select * from car");
		
		
		List <Car> carlist = new ArrayList<Car>();
		
		while(resultset.next()){
		
			int carnumber = resultset.getInt("carnumber");
			String carmodel= resultset.getString("carmodel");
			String cartype=resultset.getString("cartype");
			int caryear=resultset.getInt("caryear");
			
			Car car = new Car(carnumber, carmodel, cartype, caryear);
			
			
			
			carlist.add(car);
		}
		
		return carlist;
	
	} catch(Exception e){
			throw new DaoException(e);
		}
	
	finally
	{
		try {
		if(resultset!=null){
			resultset.close();
			}
		
			closeResources(statement,connection);
	
	}	catch (SQLException e) {	
		e.printStackTrace();	
	}
	}
	}
		
	
	
	private void closeResources(Statement statement, Connection connection){
		
		try {
			if(statement!=null){
				statement.close();
			}
			
			if(connection!=null){
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

private Connection getConnection(){
		
		try {
			 
			Class.forName("oracle.jdbc.OracleDriver");
			}catch (ClassNotFoundException e){
				throw new DaoException(e);
			}
		
		try {
			return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "mydb","oracle12");
		} catch (SQLException e) {
			throw new DaoException(e);
		}
		
		
	}


public void createCar(Car car) {
	


	Connection connection = null;
	PreparedStatement statement = null;
	
	try{
		
	
	connection = getConnection();
	statement=connection.prepareStatement("insert into car values(?,?,?,?)");
	
	
	statement.setInt(1,car.getCarnumber());
	statement.setString(2,car.getCarmodel());
	statement.setString(3,car.getCartype());
	statement.setInt(4,car.getCaryear());
	
	
	
	statement.execute();
	
	
} catch(Exception e){
		throw new DaoException(e);
	}

finally
{
closeResources(statement,connection);
}


}





}















	

